﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Grids;
using VAdvantage.Classes;
using System.Windows.Data;
using VAdvantage.DataBase;

namespace VAdvantage.Controls
{
    public partial class VDateTimePicker : UserControl,IControl,IEditingControl
    {
        #region "Declaration"

        private String _columnName;
        protected int _displayType = DisplayType.Date;
        private String _title;
        private bool _dateSetting;
        private bool _timeSetting;
        private String _oldText;
        private String _initialText;
        //
        //
        private bool _readOnly;
        private bool _mandatory;
        private GridField _field;
        ContextMenu popupMenu = new ContextMenu();
        public event EventHandler VetoableChangeListener;

        private bool _focus;

        private Binding binding = null;

        
        #endregion


        public static readonly DependencyProperty DateTimeValueProperty =
        DependencyProperty.Register("DateTimeValue", typeof(DateTime?), typeof(VAdvantage.Controls.VDateTimePicker), new PropertyMetadata((o, e) =>
        {
            ((VDateTimePicker)o).Value = (DateTime?)e.NewValue;

        }));


        public DateTime? DateTimeValue
        {
            get
            {
                return ((DateTime?)GetValue(VDateTimePicker.DateTimeValueProperty));
            }
            set
            {
                SetValue(VDateTimePicker.DateTimeValueProperty, value);
            }
        }


        public VDateTimePicker()
        {
            InitializeComponent();
        }

        public VDateTimePicker(string columnName, bool mandatory, bool isReadOnly, bool isUpdateable, int displayType, string title):this()
        {
           // SetCultureFormat();
           // this.Format = DateTimePickerFormat.Custom;
            //this.Name = columnName;
            _columnName = columnName;
            _title = title;
            _displayType = displayType;
            _readOnly = isReadOnly;
            _mandatory = mandatory;

            //	ReadWrite
            if (isReadOnly || !isUpdateable)
                this.IsEnabled = false;
            else
                this.IsEnabled = true;

            //this.Width = 300;

            // set contextmenu of control
            //this.ContextMenuStrip = popupMenu;

            //ContextMenuService.SetContextMenu(this, popupMenu);

            SetFormat();
            //this.Value = null;
            //this.DataBindings.DefaultDataSourceUpdateMode = DataSourceUpdateMode.Never;
        }


        #region Property

        public DateTime? Value
        {

            get
            {
                return (DateTime?)GetValue();

            }
            set
            {
                    SetValue(value);
            }
        }

        #endregion

        /// <summary>
        /// Set Cutom Format according to _display type
        /// </summary>
        private void SetFormat()
        {
            if (DisplayType.DateTime == _displayType)
            {
                date.Visibility = System.Windows.Visibility.Visible;
                time.Visibility = System.Windows.Visibility.Visible;
                
                date.SelectedDateChanged += dateSelectedDateChanged;
                time.ValueChanged += timeValueChanged;

                date.GotFocus += GotFocus;
                date.LostFocus += LostFocus;

                time.GotFocus += GotFocus;
                time.LostFocus += LostFocus;

            }
            else if (DisplayType.Time == _displayType)
            {
                date.Visibility = System.Windows.Visibility.Collapsed;
                time.Visibility = System.Windows.Visibility.Visible;
                time.ValueChanged += timeValueChanged;
                time.GotFocus += GotFocus;
                time.LostFocus += LostFocus;
                
            }
            else
            {
                date.Visibility = System.Windows.Visibility.Visible;
                time.Visibility = System.Windows.Visibility.Collapsed;
                date.SelectedDateChanged += dateSelectedDateChanged;

                date.GotFocus += GotFocus;
                date.LostFocus += LostFocus;
            }
        }

        void LostFocus(object sender, RoutedEventArgs e)
        {
            //_focus = false;
        }

        void GotFocus(object sender, RoutedEventArgs e)
        {
            _focus = true;
        }


       

        protected override void OnLostFocus(RoutedEventArgs e)
        {
            _focus = false;
        }


        #region IControl

        

        public int GetDisplayType()
        {
            return _displayType;
        }

        public void SetDisplayType(int displayType)
        {
            _displayType = displayType;
        }

        public bool GetIsReadonly()
        {
            return _readOnly;
        }

        public void SetReadOnly(bool readOnly)
        {
            _readOnly = readOnly;

            if (readOnly && _mandatory && this.Value == null)
            {
                this.IsEnabled = true;
                SetControlColors(GlobalVariable.MANDATORY_TEXT_BACK_COLOR);
                //this.  _backColor = DataBase.GlobalVariable.MANDATORY_TEXT_BACK_COLOR;
                _readOnly = false;
                return;
            }

            this.IsEnabled = !readOnly;

            _readOnly = readOnly;

            if (readOnly)
            {
                SetControlColors(GlobalVariable.READONLY_TEXT_BACK_COLOR);
            }
            else
            {
               SetControlColors(GlobalVariable.NORMAL_TEXT_BACK_COLOR);
                SetColor();
            }
        }

        private void SetColor()
        {
            if (_mandatory && !_readOnly)
            {
                if (this.Value == null)
                {
                    SetControlColors(GlobalVariable.MANDATORY_TEXT_BACK_COLOR);
                }
                else
                {
                    SetControlColors(GlobalVariable.NORMAL_TEXT_BACK_COLOR);
                    if (_field != null)
                    {
                        _field.SetError(false);
                    }
                }
            }
        }


        SolidColorBrush colorDate = new SolidColorBrush(Colors.White);
        SolidColorBrush colorTime = new SolidColorBrush(Colors.White);

        private void SetControlColors(Color color)
        {
            colorDate.Color = color;
            colorTime.Color = color;

            date.Background = colorDate;
            time.Background = colorTime;
        }

        public Grids.GridField GetField()
        {
            return _field;
        }

        public void SetField(Grids.GridField mField)
        {
            _field = mField;
        }

        public string GetName()
        {
            return _columnName;
        }

        public void SetName(string name)
        {
            _columnName = name;
        }

        public string GetText()
        {
            return Convert.ToString(this.Value);
        }

        public object GetValue()
        {
            if (_displayType == DisplayType.Time)
            {
                return time.GetSelectedValue();
            }
            else
            {
                DateTime? dTime = null;
                if (_displayType == DisplayType.Date)
                {
                    if (date.SelectedDate != null)
                    {
                        dTime = new DateTime(date.SelectedDate.Value.Ticks, DateTimeKind.Local);
                    }
                }

                else
                {
                    long ticks = 0;
                    if (date.SelectedDate != null)
                    {
                        ticks += date.SelectedDate.Value.Ticks;
                    }

                    if (time.GetSelectedValue() != null)
                    {
                        ticks += ((DateTime)time.GetSelectedValue()).TimeOfDay.Ticks;
                    }

                    if (ticks > 0)
                    {
                        dTime = new DateTime(ticks,DateTimeKind.Local);
                        
                    }
                    else
                    {
                        dTime = null;
                    }
                }
                return dTime;
            }
        }

        public void SetValue(object value)
        {
            //_dateSetting = true;
           // _timeSetting = true;

            if (value == null || !(value is DateTime))
            {
                    date.SelectedDate = null;
                    time.Value = null;
                    _dateSetting = false;
                    _timeSetting = false;
                    return;
            }

            DateTime dt = (DateTime)value;
             if (_displayType == DisplayType.Date)
            {
                date.SelectedDate = dt.Date;
            }
            else if (_displayType == DisplayType.Time)
            {
                time.Value = new DateTime(1900, 1, 1, dt.Hour, dt.Minute, 0);
            }
            else
            {
                date.SelectedDate = dt.Date;
                time.Value = new DateTime(1900, 1, 1, dt.Hour, dt.Minute, 0);
            }
             SetColor();
             
        }

        public bool GetIsMandatory()
        {
            return _mandatory;
        }

        public void SetIsMandatory(bool value)
        {
            _mandatory = value;
        }

        public void SetBackGround(bool value)
        {
            //throw new NotImplementedException();
        }

        public string GetSelectedText()
        {
           // throw new NotImplementedException();
            return _title;
        }

        public bool IsDisabled()
        {
            return _readOnly;
        }

        public void SetDisabled(bool disabled)
        {
            _readOnly = disabled;
            this.IsEnabled = !disabled;
        }

        public int GetTabIndex()
        {
            return this.TabIndex;
        }

        public void SetTabindex(int tabindex)
        {
            this.TabIndex = tabindex;
        }

        public bool Multiline
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public bool Visible
        {
            get
            {
                return this.Visibility == System.Windows.Visibility.Visible;
            }
            set
            {
                this.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            }
        }

        public bool Focused
        {
            get { return _focus || IsDropDownOpened() ; }
        }

        private bool IsDropDownOpened()
        {
            return date.IsDropDownOpen || time.IsDropDownOpen;
        }
        

        public string BindValue
        {
            set
            {
                binding = new Binding(value);
                binding.Mode = BindingMode.OneWay;
                this.SetBinding(VDateTimePicker.DateTimeValueProperty, binding);
            }   
        }

        public void Dispose()
        {
            popupMenu = null;
            time.ValueChanged -= timeValueChanged;
            date.SelectedDateChanged -= dateSelectedDateChanged;
            binding = null;

            date.GotFocus -= GotFocus;
            date.LostFocus -= LostFocus;

            time.GotFocus -= GotFocus;
            time.LostFocus -= LostFocus;
        }

        #endregion


        void timeValueChanged(object sender, RoutedPropertyChangedEventArgs<DateTime?> e)
        {
            //if (_timeSetting)
            //{
            //    _timeSetting = false;
            //    return;
            //}

            FireVetoableChanged();
        }

        void dateSelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            //if (_dateSetting)
            //{
            //     _dateSetting = false;
            //    return;
            //}
            FireVetoableChanged();
        }

        private void FireVetoableChanged()
        {
            //if (EditingControlDataGridView != null)
            //{
            //    //EditingControlDataGridView.RaiseCellValueChanged(this);
            //    //object value = GetValue();
            //    //_field.SetValue(value);
            //    //((DataUtil.DataObject)EditingControlDataGridView.SelectedItem).SetFieldValue(_columnName.ToUpper(), value);
            //}
            //else
            //{
            SetColor();
            if (VetoableChangeListener != null && Focused)
            {
                VetoableChangeListener(this, EventArgs.Empty);
            }
            //    }
            //}
        }

        public VDataGrid EditingControlDataGridView
        {
            get;
            set;
        }

        public void SetValueInDataGridColumn(object value)
        {
            SetValue(value);
        }
    }
}
